import fs from 'fs'
import path from 'path'
import sharp from 'sharp';
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'
import { ResizeImageCommand, ResizeImageSize } from './resize-image.command';


@CommandHandler(ResizeImageCommand)
export class ResizeImageCommandHandler implements ICommandHandler<ResizeImageCommand> {
  async execute(command: ResizeImageCommand) {
    // 准备数据
    const { filepath, filename, sizes, dest } = command.params

    // 创建目录
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest, { recursive: true })
    }

    // 读取文件
    const image = sharp(filepath)
    const metadata = await image.metadata()

    // 缩放头像
    const resize = (size: ResizeImageSize) => {
      if (metadata.width < size.width || metadata.height < size.height) {
        return
      }
      // avatar-suffix
      const resizedImagePath = path.join(dest, `${filename}-${size.suffix}`)
      return image.resize(size.width, size.height, { fit: size.fit }).toFile(resizedImagePath)
    }

    return Promise.all(sizes.map(resize))
  }
}